package com.woniuxy.shiro_config;

import com.woniuxy.filtes.JWTFilter;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;


@Configuration
public class ShiroConfig {
    //类似之前的ini配置文件shiro-realm.ini的配置，配置默认的安全管理器，并注入我们的自定义域
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(MyJWTRealm myJWTRealm){
        return new DefaultWebSecurityManager(myJWTRealm);
    }
    //shiro的过滤器配置，注入上面创建的SecurityManager
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //1.注入 安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //2.配置我们的过滤器，只是注册而已，还未生效，因为，我们要 拦截某个url吧
        Map<String, Filter> filters = new HashMap<>();
        filters.put("jwt",new JWTFilter());
        shiroFilterFactoryBean.setFilters(filters);
        //3.开始配置 url 映射上面的key：  jwt
        Map<String, String> filterChainDefinitionMap = new HashMap<>();
        //3.2 登录请求要放行,anon表示匿名访问
        //3.1 jwt这个key的过滤器，拦截所有请求
        filterChainDefinitionMap.put("/**","jwt");
        filterChainDefinitionMap.put("/login","anon");
        filterChainDefinitionMap.put("/401","anon");
        //我们还需要配置一个 拦截某些url的方案，配置过滤器链
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }
}

